from enum import Enum
from typing import Optional, List
from pydantic import BaseModel, Field, field_validator
import re

class PhysicalState(Enum):
    SOLID = 1
    LIQUID = 2
    GAS = 3

class Chemical(BaseModel):
    """化学品核心实体"""
    id: str = Field(..., min_length=3, description="唯一标识符（CAS或内部ID）")
    name: str = Field(..., max_length=100, description="中文名称")
    en_name: str = Field(..., max_length=100, description="英文名称")
    cas: Optional[str] = Field(None, description="CAS登记号")
    un: Optional[str] = Field(None, pattern=r'^UN\d{4}$', description="UN编号")
    molecular_formula: str = Field(..., description="分子式")
    physical_state: PhysicalState = Field(..., description="物理状态")
    # aliases: List[str] = Field(default_factory=list, description="别名列表")

    @field_validator('cas')
    @classmethod
    def validate_cas(cls, v: Optional[str]) -> Optional[str]:
        if v is None:
            return v

        if not re.fullmatch(r'^\d{2,7}-\d{2}-\d$', v):
            raise ValueError("Invalid CAS number format")

        parts = v.split('-')
        if len(parts[0]) < 2 or len(parts[0]) > 7:
            raise ValueError("CAS first segment must be 2-7 digits")
        if len(parts[1]) != 2:
            raise ValueError("CAS second segment must be 2 digits")

        return v

class Hazard(BaseModel):
    """危害特性实体"""
    name: str = Field(..., description="危害名称")
    code: str = Field(..., pattern=r'^(GHS|H)\d+$', description="GHS/H代码")
    severity: int = Field(1, ge=1, le=5, description="危险等级")
    icon: Optional[str] = Field(None, description="图标路径")

    @field_validator('severity')
    @classmethod
    def check_severity(cls, v: int) -> int:
        if v > 3:
            print(f"警告：高风险等级 {v}！需要特殊处理")
        return v